/**
 * Project Name:cas-web
 * File Name:CusUsernamePasswordAuthenticationHandler.java
 * Package Name:com.paas.podinns.cassever.service
 * Date:2015年10月30日下午2:11:05
 * author Administrator
 *
 */
package com.paas.service.modules.sso.cas.service.handeler;

import java.security.GeneralSecurityException;

import javax.security.auth.login.AccountException;
import javax.security.auth.login.AccountNotFoundException;
import javax.security.auth.login.FailedLoginException;

import org.apache.commons.lang.StringUtils;
import org.jasig.cas.authentication.HandlerResult;
import org.jasig.cas.authentication.PreventedException;
import org.jasig.cas.authentication.handler.PasswordEncoder;
import org.jasig.cas.authentication.principal.SimplePrincipal;
import org.springframework.beans.factory.annotation.Autowired;

import com.paas.base.modules.utils.lang.StringUtilExt;
import com.paas.service.modules.sso.cas.service.exception.NoAuthException;
//import com.paas.service.modules.sso.cas.service.service.AccountService;

/**
 * @ClassName: CusUsernamePasswordAuthenticationHandler 
 * @Desc（描述这个类的做什么的）: 
 * 		这里写自定义的登陆验证逻辑
 * @date: 2015年10月30日 下午2:11:05
 * @author zhouziqiang
 * @version 
 */
public class CusUsernamePasswordAuthenticationHandler extends CusAbstractUsernamePasswordAuthenticationHandler {
	/**
	 * TODO 简单描述该方法的实现功能（可选）.
	 * @see org.jasig.cas.authentication.handler.support.AbstractUsernamePasswordAuthenticationHandler#authenticateUsernamePasswordInternal(org.jasig.cas.authentication.UsernamePasswordCredential)
	 */
//	@Autowired
//	private AccountService accountService;
	
	@Autowired
	private PasswordEncoder passwordEncoder;
	
    /****
     * 验证登录是否通过
     */
	@Override
	protected HandlerResult authenticateUsernamePasswordInternal(
			CusUsernamePasswordCredential credential)
					throws GeneralSecurityException, PreventedException {

		String username = credential.getUsername();
		String password = credential.getPassword();
		if(StringUtilExt.isEmpty(username)||StringUtilExt.isEmpty(password)){
			throw new FailedLoginException();
		}
		String encryptedPassword = passwordEncoder.encode(password);
		
		String systemId = credential.getSystemId();
		String code =  "";//============accountService.checkAccount(username, encryptedPassword,systemId);
		
		 if(code.equals("-3")){
			  //账户不存在
			 
			  throw new AccountNotFoundException();
		  }else if(code.equals("-4")){
			  //密码错误
			 
			  throw new FailedLoginException();
		  }else if(code.equals("-2")){
			  //权限不足
			 
			  throw new NoAuthException("权限不足");
		  }else if(code.equals("-1")){
			  throw new AccountException("服务异常");
		  }
		return createHandlerResult(credential, new SimplePrincipal(username ), null);
			
			
	}
}
